export function drag(
	elem: HTMLElement,
	evt: PointerEvent,
	onMove: (evt: PointerEvent, distance: { x: number; y: number }) => void,
	onClose?: (evt: PointerEvent, speed: { x: number; y: number }) => void,
) {
	const target = evt.target as HTMLElement;
	const startX = evt.clientX;
	const startY = evt.clientY;
	const startTime = Date.now();
	evt.preventDefault();
	evt.stopPropagation();
	const pointerId = evt.pointerId;
	target.setPointerCapture(pointerId);
	const move = (evt: PointerEvent) => {
		if (evt.pointerId === pointerId) {
			evt.preventDefault();
			evt.stopPropagation();
			onMove(evt, { x: evt.clientX - startX, y: evt.clientY - startY });
		}
	};
	const close = (evt: PointerEvent) => {
		if (evt.pointerId === pointerId) {
			target.releasePointerCapture(pointerId);
			elem.removeEventListener('pointermove', move);
			elem.removeEventListener('pointercancel', close);
			elem.removeEventListener('pointerup', close);
			evt.preventDefault();
			evt.stopPropagation();
			const dx = evt.clientX - startX;
			const dy = evt.clientY - startY;
			const currentTime = Date.now();
			const speedX = dx / (currentTime - startTime);
			const speedY = dy / (currentTime - startTime);
			onClose?.(evt, { x: speedX, y: speedY });
		}
	};
	elem.addEventListener('pointermove', move);
	elem.addEventListener('pointercancel', close);
	elem.addEventListener('pointerup', close);
}
